<template>
  <div>
    <div><h1>商品列表</h1></div>
    <div>
      <el-button type="primary" @click="OnAddProd">添加商品</el-button>
      <el-button type="danger" @click="OndeleteBatch">批量删除</el-button>
    </div>
    <div>
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="请输入关键词">
          <el-input
            v-model="searchForm.keyWord"
            placeholder="请输入"
            clearable
          />
        </el-form-item>
        <el-form-item label="请输入ID">
          <el-input
            v-model="searchForm.prodId"
            placeholder="请输入"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadList">搜索</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div>
      <el-table
        :data="prodList"
        stripe
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="prodId" label="ID" width="50" />
        <el-table-column prop="prodSpu" label="SPU" width="100" />
        <el-table-column prop="kindName" label="种类" width="100" />
        <el-table-column prop="typeName" label="类型" width="100" />
        <el-table-column prop="prodName1" label="名称" width="100" />
        <el-table-column prop="brandName" label="品牌" width="100" />
        <el-table-column prop="unitName" label="单位" width="100" />
        <el-table-column prop="tagName" label="标签" width="100" />
        <el-table-column prop="appr" label="供应商" width="100" />
        <el-table-column prop="prodStatus" label="商品状态" width="100">
          <template #default="scope">
            <span v-if="scope.row.prodStatus == 0">草稿</span>
            <span v-if="scope.row.prodStatus == 1">待审核</span>
            <span v-if="scope.row.prodStatus == 2">已上线</span>
            <span v-if="scope.row.prodStatus == 3">已下线</span>
            <span v-if="scope.row.prodStatus == 4">已缺货</span>
          </template>
        </el-table-column>
        <el-table-column prop="prodImage" label="图片">
          <template #default="scope">
            <el-image
              v-if="scope.row.prodImage != null && scope.row.prodImage != ''"
              :src="scope.row.prodImage"
              style="width: 50px; height: 50px"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="录入时间" width="180" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button
              type="danger"
              size="small"
              @click="OndeleteProd(scope.row)"
              >删除</el-button
            >
            <el-button type="primary" @click="OnAddProd">商品</el-button>
            <el-button type="success" @click="OnAddAtta(scope.row)"
              >商品附件</el-button
            >
            <el-button type="primary" @click="OnBuyProd(scope.row)"
              >购买</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div style="margin-top: 20px">
      <div class="demo-pagination-block">
        <el-pagination
          v-model:current-page="searchForm.pageNum"
          v-model:page-size="searchForm.pageSize"
          :page-sizes="[2, 4, 6, 8]"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <div>
      <el-dialog v-model="dialogFormVisible" title="添加商品" width="500">
        <el-form :model="form" ref="ruleFormRef" :rules="rules">
          <el-form-item
            label="商品类型"
            :label-width="formLabelWidth"
            prop="prodKind"
          >
            <el-radio-group v-model="form.prodKind">
              <el-radio
                v-for="item in KindList"
                :value="item.dictValue"
                :key="item.dictValue"
                >{{ item.dictName }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label="商品分类"
            :label-width="formLabelWidth"
            prop="prodType"
          >
            <el-tree-select
              v-model="form.prodType"
              :data="typeList"
              :render-after-expand="false"
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item
            label="商品名称"
            :label-width="formLabelWidth"
            prop="prodName"
          >
            <el-input v-model="form.prodName" autocomplete="off" />
          </el-form-item>
          <el-form-item
            label="SPU"
            :label-width="formLabelWidth"
            prop="prodSpu"
          >
            <el-input v-model="form.prodSpu" autocomplete="off" />
          </el-form-item>
          <el-form-item
            label="商品品牌"
            :label-width="formLabelWidth"
            prop="brandId"
          >
            <el-select
              v-model="form.brandId"
              placeholder="请选泽"
              size="large"
              style="width: 240px"
            >
              <el-option
                v-for="item in brandList"
                :key="item.brandId"
                :label="item.brandName"
                :value="item.brandId"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="商品单位"
            :label-width="formLabelWidth"
            prop="unitId"
          >
            <el-select
              v-model="form.unitId"
              placeholder="请选泽"
              size="large"
              style="width: 240px"
            >
              <el-option
                v-for="item in UnitList"
                :key="item.dictValue"
                :label="item.dictName"
                :value="item.dictValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="商品标签"
            :label-width="formLabelWidth"
            prop="tagId"
          >
            <el-select
              v-model="form.tagId"
              placeholder="请选泽"
              size="large"
              style="width: 240px"
            >
              <el-option
                v-for="item in flagList"
                :key="item.dictValue"
                :label="item.dictName"
                :value="item.dictValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="供应商"
            :label-width="formLabelWidth"
            prop="appr"
          >
            <el-input v-model="form.appr" autocomplete="off" />
          </el-form-item>
          <el-form-item
            label="商品缩略图"
            :label-width="formLabelWidth"
            prop="prodImage"
          >
            <el-upload
              class="avatar-uploader"
              action="http://localhost:10010/shop/type/uploadImage"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :headers="headers"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="submitForm(ruleFormRef)">
              添加
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
    <div>
      <el-dialog v-model="AttaFormVisible" title="添加商品附件" width="500">
        <el-form :model="formAtta">
          <el-form-item label="商品轮播图片" :label-width="AttaLabelWidth">
            <el-upload
              v-model:file-list="fileList"
              action="http://localhost:10010/shop/type/uploadImage"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :headers="headers"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>

            <el-dialog v-model="dialogVisible">
              <img w-full :src="dialogImageUrl" alt="Preview Image" />
            </el-dialog>
          </el-form-item>
          <el-form-item label="商品视频" :label-width="AttaLabelWidth">
            <el-upload
              v-model:file-list="fileListfile"
              class="upload-demo"
              action="http://localhost:10010/shop/type/uploadImage"
              multiple
              :on-preview="handlePreview"
              :on-remove="handleRemovefile"
              :before-remove="beforeRemove"
              :limit="1"
              :on-exceed="handleExceed"
              :headers="headers"
            >
              <el-button type="primary">上传视频</el-button>
              <template #tip>
                <div class="el-upload__tip">
                  作用于商品详情页顶部轮插的视频介绍最大限制20MB,
                </div>
              </template>
            </el-upload>
          </el-form-item>
          <el-form-item label="上架时间" :label-width="AttaLabelWidth">
            <el-radio-group v-model="formAtta.upFlag">
              <el-radio :value="0">立即上架</el-radio>
              <el-radio :value="1">定时上架</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label="上架时间"
            :label-width="AttaLabelWidth"
            v-if="formAtta.upFlag == 1"
          >
            <el-date-picker
              v-model="formAtta.upTime"
              type="datetime"
              placeholder="请选择定时上架时间"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item label="定时下架" :label-width="AttaLabelWidth">
            <el-switch
              v-model="formAtta.downFlag"
              :active-value="1"
              :inactive-value="0"
            />
          </el-form-item>
          <el-form-item
            label="下架时间"
            :label-width="AttaLabelWidth"
            v-if="formAtta.downFlag == 1"
          >
            <el-date-picker
              v-model="formAtta.downTime"
              type="datetime"
              placeholder="请选择定时下架时间"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">放弃</el-button>
            <el-button type="primary" @click="OnsubmitAddProdAtta">
              提交
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ElMessage } from "element-plus";
import {
  ProdList,
  getDictList,
  SelecttreeList,
  BrandList,
  GetAddProd,
  AddprodAtta,
  deleteBatchProd,
  deleteProd,
} from "../api/api";
import { onMounted, reactive, ref } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import type { UploadProps } from "element-plus";

import type { UploadUserFile } from "element-plus";
const ruleFormRef = ref<FormInstance>();
const dialogFormVisible = ref(false);
const formLabelWidth = "140px";
const AttaFormVisible = ref(false);
const AttaLabelWidth = "140px";
const prodList = ref([]);
const typeList = ref([]);
const searchForm = ref({
  keyWord: "",
  pageNum: 1,
  pageSize: 2,
  prodId: null,
});
const total = ref(0);
//多图片变量
const fileList = ref<UploadUserFile[]>([]);
const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const multipleSelection = ref<any[]>([]);

//文件上传变量
import { ElMessageBox } from "element-plus";
const fileListfile = ref<UploadUserFile[]>([]);
const form = ref({
  appr: "",
  brandId: null,
  prodId: null,
  prodImage: "",
  prodKind: null,
  prodName: "",
  prodSpu: "",
  prodStatus: null,
  prodType: null,
  tagId: null,
  unitId: null,
});

const formAtta = ref({
  attaImages: "",
  attaVideo: "",
  downFlag: null,
  downTime: "",
  prodId: null,
  upFlag: null,
  upTime: "",
});

const KindList = ref([]);
const UnitList = ref([]);
const flagList = ref([]);
const brandList = ref([]);

const headers = ref({
  token: sessionStorage.getItem("token"),
});

//购买商品

const OnBuyProd = (row: any) => {};

//删除商品
const OndeleteProd = (row: any) => {
  ElMessageBox.confirm("删除数据后数据无法恢复确认要删除吗?", "警告", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      deleteProd(row.prodId).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("删除成功");
          loadList();
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
};

//批量删除
const OndeleteBatch = () => {
  if (multipleSelection.value.length <= 0) {
    ElMessage.error("请选择数据");
    return;
  }
  let ids: any = [];
  multipleSelection.value.forEach((item) => {
    ids.push(item.prodId);
  });
  ElMessageBox.confirm("删除数据后数据无法恢复确认要删除吗?", "警告", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      deleteBatchProd(ids).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("批量删除成功");
          loadList();
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消批量删除",
      });
    });
};

//多选方法
const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val;
};

//多图片方法
const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
};

//文件上传方法
const handleRemovefile: UploadProps["onRemove"] = (file, uploadFiles) => {
  console.log(file, uploadFiles);
};

const handlePreview: UploadProps["onPreview"] = (uploadFile) => {
  console.log(uploadFile);
};

const handleExceed: UploadProps["onExceed"] = (files, uploadFiles) => {
  ElMessage.warning(
    `The limit is 3, you selected ${files.length} files this time, add up to ${
      files.length + uploadFiles.length
    } totally`
  );
};

const beforeRemove: UploadProps["beforeRemove"] = (uploadFile, uploadFiles) => {
  return ElMessageBox.confirm(
    `Cancel the transfer of ${uploadFile.name} ?`
  ).then(
    () => true,
    () => false
  );
};

const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};

//提交添加商品附件
const OnsubmitAddProdAtta = () => {
  //添加多图片

  let attaImages: any = [];
  fileList.value.forEach((item) => {
    attaImages.push(item.response.data);
  });
  formAtta.value.attaImages = JSON.stringify(attaImages);
  //上传视频
  if (fileListfile.value.length <= 0) {
    ElMessage.error("请选择视频");
    return;
  }

  formAtta.value.attaVideo = fileListfile.value[0].response.data;

  AddprodAtta(formAtta.value).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success("添加成功");
      AttaFormVisible.value = false;
      loadList();
    } else {
      ElMessage.error(res.data.msg);
    }
  });
};

//显示添加商品附件框
const OnAddAtta = (row: any) => {
  fileList.value = [];
  fileListfile.value = [];
  formAtta.value = {
    attaImages: "",
    attaVideo: "",
    downFlag: null,
    downTime: "",
    prodId: null,
    upFlag: null,
    upTime: "",
  };
  console.log(row);
  formAtta.value.prodId = row.prodId;
  AttaFormVisible.value = true;
};

//图片上传
const imageUrl = ref("");

const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  imageUrl.value = response.data;
};

//图片校验
const checkAge = (rule: any, value: any, callback: any) => {
  if (imageUrl.value == null || imageUrl.value == "") {
    return callback(new Error("请选泽商品缩略图"));
  } else {
    return callback();
  }
};

//必填校验
const rules = reactive({
  prodName: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
  prodSpu: [{ required: true, message: "请输入SPU", trigger: "blur" }],
  prodKind: [
    {
      required: true,
      message: "请选泽",
      trigger: "change",
    },
  ],
  prodType: [
    {
      required: true,
      message: "请选泽商品分类",
      trigger: "change",
    },
  ],
  brandId: [
    {
      required: true,
      message: "请选泽商品品牌",
      trigger: "change",
    },
  ],
  unitId: [
    {
      required: true,
      message: "请选泽商品单位",
      trigger: "change",
    },
  ],
  tagId: [
    {
      required: true,
      message: "请选泽商品标签",
      trigger: "change",
    },
  ],
  appr: [
    {
      required: true,
      message: "请选泽商品供应商",
      trigger: "change",
    },
  ],
  prodImage: [{ required: true, validator: checkAge, trigger: "blur" }],
});

//添加商品方法
const OnaddProd = () => {
  form.value.prodImage = imageUrl.value;
  GetAddProd(form.value).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success("添加商品成功");
      dialogFormVisible.value = false;
      loadList();
    } else {
      ElMessage.error(res.data.msg);
    }
  });
};

//校验提交
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");
      OnaddProd();
    } else {
      console.log("error submit!", fields);
    }
  });
};

//显示添加商品框
const OnAddProd = () => {
  form.value = {
    appr: "",
    brandId: null,
    prodId: null,
    prodImage: "",
    prodKind: null,
    prodName: "",
    prodSpu: "",
    prodStatus: null,
    prodType: null,
    tagId: null,
    unitId: null,
  };
  imageUrl.value = "";
  dialogFormVisible.value = true;
};

//分页
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  searchForm.value.pageSize = val;
  loadList();
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  searchForm.value.pageNum = val;
  loadList();
};

const loadList = () => {
  ProdList(searchForm.value).then((res) => {
    if (res.data.code == 200) {
      prodList.value = res.data.data.records;
      total.value = res.data.data.total;
    }
  });
};

onMounted(() => {
  loadList();
  //商品类型
  getDictList(1).then((res) => {
    if (res.data.code == 200) {
      KindList.value = res.data.data;
    }
  });
  //商品单位
  getDictList(2).then((res) => {
    if (res.data.code == 200) {
      UnitList.value = res.data.data;
    }
  });
  //商品标签
  getDictList(3).then((res) => {
    if (res.data.code == 200) {
      flagList.value = res.data.data;
    }
  });
  //商品品牌列表
  BrandList().then((res) => {
    brandList.value = res.data.data;
  });
  //商品类型
  SelecttreeList().then((res) => {
    typeList.value = res.data.data;
  });
});
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
